export const getApiKey = async (): Promise<string> => {
  console.log('=== getApiKey 调试信息 ===');
  console.log('当前环境:', process.env.NODE_ENV);

  if (process.env.NODE_ENV === 'development') {
    console.log('开发环境模式');

    // 开发环境：优先从public/config.json读取，然后从localStorage读取
    try {
      console.log('尝试读取 /config.json');
      const response = await fetch('/config.json');
      if (response.ok) {
        const fileConfig = await response.json();
        console.log('从 config.json 读取到配置:', fileConfig);
        if (fileConfig.apiKey) {
          console.log('返回 config.json 中的 apiKey:', fileConfig.apiKey);
          return fileConfig.apiKey;
        }
      } else {
        console.log('config.json 读取失败，状态码:', response.status);
      }
    } catch (error) {
      console.log('无法读取config.json文件，错误:', error);
      console.log('尝试从localStorage读取');
    }

    // 备用：从localStorage读取
    console.log('检查 localStorage 中的配置');
    const savedConfig = localStorage.getItem('picshare-config');
    console.log('localStorage 中的原始配置:', savedConfig);

    if (savedConfig) {
      const config = JSON.parse(savedConfig);
      console.log('从 localStorage 解析的配置:', config);
      const apiKey = config.apiKey || '';
      console.log('返回 localStorage 中的 apiKey:', apiKey);
      return apiKey;
    }

    console.log('未找到任何配置，返回空字符串');
    return '';
  } else {
    console.log('生产环境模式');
    if (window.electronAPI && window.electronAPI.getConfig) {
      console.log('通过 electronAPI 获取配置');
      const config = await window.electronAPI.getConfig();
      console.log('electronAPI 返回的配置:', config);
      const apiKey = config.apiKey || '';
      console.log('返回生产环境的 apiKey:', apiKey);
      return apiKey;
    }
    console.log('未找到 electronAPI，返回空字符串');
    return '';
  }
};